package it.unipi.di.rasip.gui.chat;

import java.util.Vector;

import it.unipi.di.rasip.utils.Color;

import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;

public class ChatMessage {
	String username;
	String message;
	Font font;
	
	Color usernameColor;
	Color messageColor;
	
	public ChatMessage() {
		font = Font.getDefaultFont();
	}
	
	public ChatMessage(String username, String message) {
		this();
		this.username = username;
		this.message = message;
	}
	
	public int drawMessage(Graphics g, Font f, int x, int y, int maxWidth) {
		String us = this.getUsername()+":";
		int msg_x = f.stringWidth(us) + 5;
		
		//Suddivido la stringa su piu` righe se necessario
		int last_space_index = 0;
		int last_start_char = 0;
		int countX = msg_x;
		int startX = 5;
		int strLen = this.message.length();
		Vector lines = new Vector();
		for (int i=0; i<strLen; i++) {
			char c = this.message.charAt(i);
			int charWidth = f.charWidth(c);
			if(c == ' ') {
				last_space_index = i;
				continue;
			}
			//System.out.println(countX);
			if((countX + charWidth) > maxWidth) { //Riga successiva
				lines.addElement(this.message.substring(last_start_char, last_space_index));
				last_start_char = last_space_index;
				countX = startX + f.stringWidth(this.message.substring(last_space_index+1, i));
				continue;
			}
			countX += charWidth;
		}
		lines.addElement(this.message.substring(last_start_char));
		
		int lineHeight = f.getHeight();
		g.setColor(this.getMessageColor().getCode());
		for(int i=lines.size()-1; i>0; i--) {
			g.drawString((String)lines.elementAt(i), startX, y, Graphics.BASELINE|Graphics.LEFT);
			y -= lineHeight;
		}
		g.setColor(this.getUsernameColor().getCode());
		g.drawString(us, 3, y, Graphics.BASELINE|Graphics.LEFT);
		g.setColor(this.getMessageColor().getCode());
		g.drawString((String)lines.elementAt(0), msg_x, y, Graphics.BASELINE|Graphics.LEFT);
		
		y -= lineHeight;
		return y;
	}

	public Font getFont() {
		return font;
	}

	public void setFont(Font font) {
		this.font = font;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public Color getMessageColor() {
		return messageColor;
	}

	public void setMessageColor(Color messageColor) {
		this.messageColor = messageColor;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public Color getUsernameColor() {
		return usernameColor;
	}

	public void setUsernameColor(Color usernameColor) {
		this.usernameColor = usernameColor;
	}
}
